package com.cloud.order.controller;

import com.cloud.order.entity.Order;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Value("${spring.cloud.client.ip-address}")
    private String ip;

    @Value("${server.port}")
    private String port;

    /**
     * 测试hystrix远程调用
     *
     * @param flag
     * @return
     */
    @GetMapping("/testHystrix/{flag}")
    public Map testHystrix(@PathVariable String flag) throws InterruptedException {

        if ("0".equals(flag)) {
            // 模拟异常
            int i = 1 / 0;
        }

        if ("1".equals(flag)) {
            // 模拟阻塞
            Thread.sleep(1500);
        }

        return new HashMap() {{
            put("flag", true);
            put("message", "请求成功");
            put("statusCode", "200");
        }};
    }

    /**
     * 查询全部
     *
     * @return
     */
    @GetMapping
    public Map findAll() throws InterruptedException {

        // 模拟线程阻塞
        Thread.sleep(3000);
        return new HashMap() {{
            put("flag", true);
            put("message", "查询成功全部成功;" + ip + ":" + port);
            put("statusCode", "200");
        }};
    }


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Map findById(@PathVariable Integer id) {

        return new HashMap() {{
            put("flag", true);
            put("message", "查询成功" + ip + ":" + port);
            put("statusCode", "200");
            put("id", id);
        }};
    }

    /**
     * 新增订单
     *
     * @param order
     * @return
     */
    @PostMapping
    public Map save(@RequestBody Order order) {

        return new HashMap() {{
            put("flag", true);
            put("message", "新增成功");
            put("statusCode", "200");
            put("order", order);
        }};
    }

    /**
     * 删除订单
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public Map delete(@PathVariable Integer id) {

        return new HashMap() {{
            put("flag", true);
            put("message", "删除成功");
            put("statusCode", "200");
            put("id", id);
        }};
    }

    /**
     * @param id
     * @param order
     * @return
     */
    @PutMapping("{id}")
    public Map update(@PathVariable Integer id, @RequestBody Order order) {

        order.setId(id);
        return new HashMap() {{
            put("flag", true);
            put("message", "修改");
            put("statusCode", "200");
            put("order", order);
        }};
    }

}
